package com.baosight.risk.base.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;


/**
 * @author duanyongqiang
 */
@Slf4j
@Service
public class BaseRedis {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private RedisLock redisLock;

    /**
     * 放入value缓存类型
     *
     * @param key 键值
     * @param o   数据类型
     */
    public void setValue(String key, Object o) {
        redisTemplate.boundValueOps(key).set(o);
    }

    /**
     * 获取value缓存数据
     *
     * @param key 键值
     * @return
     */
    public Object getValue(String key) {
        return redisTemplate.boundValueOps(key).get();
    }

    /**
     * 根据键值判断缓存还存在
     *
     * @param key
     * @return
     */
    public boolean isKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 根据键删除缓存
     *
     * @param key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 根据key批量删除
     *
     * @param key
     */
    public void deleteList(String key) {
        Set<Object> keys = redisTemplate.keys(key + "*");
        redisTemplate.delete(keys);
    }


    /**
     * @param key
     * @return
     */
    public boolean louck(String key) {
        if (redisLock.lock(key, null) != 0L) {
            return false;
        } else {
            return true;
        }
    }

    public void unLouck(String key) {
        redisLock.unLock(key);
    }

    /**
     * 获取以该key开头的所有key的集合
     *
     * @param key
     * @return
     */
    public Set<Object> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }
}
